<template>
  <div>
    <van-nav-bar
      title="地址列表"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div v-if="list.length != 0">
      <van-address-list
        v-model="curren"
        :list="list"
        @add="onAdd"
        @select="onselect"
        default-tag-text="默认"
      />
    </div>
    <van-empty v-else description="暂无地址">
      <van-button round @click="onAdd" type="danger" class="bottom-button"
        >添加地址</van-button
      >
    </van-empty>
  </div>
</template>
<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      list: [],
      curren: "",
      addressinfo: {
        time: "",
        id: "",
      },
      addrelist: {},
    };
  },
  created() {
    try {
      for (let i = 0; i < this.Address.length; i++) {
        if (this.Address[i].isDefault === true) {
          this.curren = this.Address[i].id;
        }
      }
    } catch (error) {}

    this.getAddress();
  },
  activated() {
    this.getAddress();
  },
  methods: {
    onAdd() {
      this.$router.push("/addAddress");
    },
    onselect(index) {
      this.addrelist = index;
      this.curren = index.id;
      var date = new Date();

      var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

      var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      var currentFormatDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      this.addressinfo.id = index.id;
      this.addressinfo.time = currentFormatDate;
      this.editTime();
    },
    async editTime() {
      this.$store.commit("setSelectAddress", this.addrelist);
      this.$router.push("/checkout");
    },
    async getAddress() {
      const { data: res } = await this.$http.get("address", {
        params: { uid: this.emailLogin[0].userID },
      });
      if (res.status == 200) {
        res.data.forEach((item) => {
          item.isDefault = item.isDefault == 0 ? false : true;
        });
        this.list = res.data;
        this.$store.commit("setAddress", res.data);
      }
    },
  },
  computed: {
    ...mapState(["Address", "emailLogin"]),
  },
};
</script>
<style lang="less" scoped>
.van-address-list {
  padding: 0;
}
</style>